import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '../pages/Login.vue';
import Register from '../pages/register.vue';
import Sales from '../pages/sales/sales.vue';
import AfterSales from '../pages/sales/after-sales.vue';
import Reservation from '../pages/sales/reservation.vue';
import Shop from '../pages/system/shop.vue';
import Supplier from '../pages/system/supplier.vue';
import Staff from '../pages/system/staff.vue';
import Customer from '../pages/system/customer.vue';
import Department from '../pages/system/department.vue';
import Purchasing from '../pages/purchasing/index.vue';
import Inthouse from '../pages/warehouse/int.vue';
import Outhouse from '../pages/warehouse/out.vue';

export const routes = [
    {
        path: '/',
        component: () => import('../components/LayoutComponent.vue'),
        redirect: '/home',
        children: [
            {
                name: 'home',
                path: '/home',
                component: () => import('../pages/index.vue'),
                meta: { title: '首页', requiresAuth: true }
            },
            {
                name: 'sales',
                path: '/sales',
                component: Sales,
                meta: { title: '销售管理', requiresAuth: true }
            },
            {
                name: 'after-sales',
                path: '/afterSales',
                component: AfterSales,
                meta: { title: '售后服务', requiresAuth: true }
            },
            {
                name: 'reservation',
                path: '/reservation',
                component: Reservation,
                meta: { title: '预约管理', requiresAuth: true }
            },
            {
                name: 'shop',
                path: '/shop',
                component: Shop,
                meta: { title: '店铺管理', requiresAuth: true }
            },
            {
                name: 'supplier',
                path: '/Supplier',
                component: Supplier,
                meta: { title: '供应商管理', requiresAuth: true }
            },
            {
                name: 'staff',
                path: '/staff',
                component: Staff,
                meta: { title: '员工管理', requiresAuth: true }
            },
            {
                name: 'department',
                path: '/department',
                component: Department,
                meta: { title: '部门管理', requiresAuth: true }
            },
            {
                name: 'customer',
                path: '/customer',
                component: Customer,
                meta: { title: '客户管理', requiresAuth: true }
            },
            {
                name: 'purchasing',
                path: '/purchasing',
                component: Purchasing,
                meta: { title: '采购管理', requiresAuth: true }
            },
            {
                name: 'inthouse',
                path: '/inthouse',
                component: Inthouse,
                meta: { title: '入库管理', requiresAuth: true }
            },
            {
                name: 'outhouse',
                path: '/outhouse',
                component: Outhouse,
                meta: { title: '出库管理', requiresAuth: true }
            },
        ]
    },
    {
        name: 'login',
        path: '/login',
        component: Login,
        meta: { title: '登录' , requiresAuth: false }
    },
    {
        name: 'register',
        path: '/register',
        component: Register
    },
    {
        name: 'index',
        path: '/index',
        component: () => import("../pages/index.vue")
    }
]

const router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    history: createWebHashHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token') || ''
    
    // 安全地解析userInfo，避免JSON解析错误
    let userInfo = {}
    try {
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr && userInfoStr !== '{}') {
            userInfo = JSON.parse(userInfoStr)
        }
    } catch (error) {
        console.error('解析userInfo失败:', error)
        // 清除可能损坏的数据
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
    }
    
    console.log('当前token:', token)
    console.log('目标路由:', to.path)
    console.log('是否需要权限:', to.meta.requiresAuth)
    
    // 检查是否需要权限验证
    if (to.meta.requiresAuth) {
        if (!token) {
            // 没有token，跳转到登录页
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
            return
        }
        
        // 检查角色权限（如果有设置）
        if (to.meta.requiredRoles && Array.isArray(to.meta.requiredRoles) && to.meta.requiredRoles.length > 0) {
            const hasPermission = to.meta.requiredRoles.some((role: string) =>
                (userInfo as any).roles?.includes(role)
            )

            if (!hasPermission) {
                // 没有权限，可以跳转到403页面或首页
                next('/home')
                return
            }
        }
    }
    
    // 如果已经登录且访问登录页，重定向到首页
    if (to.path === '/login' && token) {
        next('/home')
        return
    }
    
    next()
})

// 全局后置钩子
router.afterEach((to, from) => {
    // // 发送页面访问统计
    // if (typeof gtag !== 'undefined') {
    //     gtag('config', 'GA_MEASUREMENT_ID', {
    //         page_path: to.path,
    //         page_title: to.meta.title
    //     })
    // }
})
export default router;